package com.irdstudio.biz.drools.common;

import org.apache.commons.lang.StringUtils;
import org.kie.api.runtime.rule.AccumulateFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;

/**
 * 征信还款状态 超类
 */
public class RepayStatusBaseAccumulate implements AccumulateFunction {

    protected static Logger log = LoggerFactory.getLogger(RepayStatusBaseAccumulate.class);

    public RepayStatusBaseAccumulate() {
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    }

    public void writeExternal(ObjectOutput out) throws IOException {
    }

    public Serializable createContext() {
        return new SumData();
    }

    public void init(Serializable context) throws Exception {
        SumData data = (SumData) context;
        data.total = 0;
    }

    /**
     * 解析还款状态 按空格分割
     * @param repayStatus 还款状态
     * @return Null return []
     */
    public String[] splitRepayStatus(String repayStatus) {
        if (StringUtils.isNotEmpty(repayStatus)) {
            String[] stats = StringUtils.split(repayStatus, " ");
            return stats;
        } else {
            return new String[0];
        }
    }

    public void accumulate(Serializable context, Object value) {
        // do nothing
        log.debug("RepayStatusBaseAccumulate do nothing");
    }

    public void reverse(Serializable context, Object value) throws Exception {

    }

    public Object getResult(Serializable context) throws Exception {
        SumData data = (SumData) context;
        return new Integer(data.total);
    }

    public boolean supportsReverse() {
        return false;
    }

    public Class<?> getResultType() {
        return Integer.class;
    }

    protected static class SumData implements Externalizable {
        public int total = 0;

        public SumData() {
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
            this.total = in.readInt();
        }

        public void writeExternal(ObjectOutput out) throws IOException {
            out.writeInt(this.total);
        }
    }
}
